# -*- encoding: utf-8 -*-
"""
@version: 1.0
@author: yang ming
@contact: 122162005@qq.com
@site: http://www.idianjia.com/
@software: PyCharm
@file: custom_field.py
@time: 2016/3/14 15:44
"""
from django.db import models
import ast


class CompressedTextField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if value is None:
            return value

        try:
            if "," in value:
                _value = value.split(",")
                _value_list = []
                for e in _value:
                    _value_list.append(e.strip())
                return _value_list

        except Exception:
            return value

    def get_prep_value(self, value):
        if value is None:
            return value

        try:
            return str(value)[1: -1]
        except Exception:
            return str(value)
            # try:
            #     tmp = value.encode('utf-8').encode('bz2').encode('base64')
            # except Exception:
            #     return value
            # else:
            #     if len(tmp) > len(value):
            #         return value
            #
            #     return tmp


class ListField(models.TextField):
    __metaclass__ = models.SubfieldBase
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return str(value) # use str(value) in Python 3

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)